package com.bjbn.service.impl;

import com.bjbn.service.HistoryDataCleanupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 历史数据清理服务实现类
 */
@Slf4j
@Service
public class HistoryDataCleanupServiceImpl implements HistoryDataCleanupService {

    @Value("${history-cleanup.retention-days:30}")
    private int retentionDays;

    @Value("${history-cleanup.enabled:true}")
    private boolean cleanupEnabled;



    @Override
    public int cleanupThsHistoryData() {
        if (!cleanupEnabled) {
            log.info("历史数据清理功能已禁用，跳过温湿度传感器数据清理");
            return 0;
        }
        
        try {
            // 计算指定天数前的日期
            LocalDate retentionDate = LocalDate.now().minusDays(retentionDays);
            String beforeDate = retentionDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

            log.info("开始清理温湿度传感器历史数据，保留{}天数据，删除{}之前的数据", retentionDays, beforeDate);

            int deletedCount = 0; //thsHisMapper.deleteHistoryDataBeforeDate(beforeDate);

            log.info("温湿度传感器历史数据清理完成，删除{}条记录", deletedCount);

            return deletedCount;
        } catch (Exception e) {
            log.error("清理温湿度传感器历史数据异常", e);
            return 0;
        }
    }

    @Override
    public int cleanupLxHistoryData() {
        if (!cleanupEnabled) {
            log.info("历史数据清理功能已禁用，跳过照度传感器数据清理");
            return 0;
        }
        
        try {
            // 计算指定天数前的日期
            LocalDate retentionDate = LocalDate.now().minusDays(retentionDays);
            String beforeDate = retentionDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            
            log.info("开始清理照度传感器历史数据，保留{}天数据，删除{}之前的数据", retentionDays, beforeDate);
            
            int deletedCount = 0; // lxHisMapper.deleteHistoryDataBeforeDate(beforeDate);
            
            log.info("照度传感器历史数据清理完成，删除{}条记录", deletedCount);
            
            return deletedCount;
        } catch (Exception e) {
            log.error("清理照度传感器历史数据异常", e);
            return 0;
        }
    }

    @Override
    public String cleanupAllHistoryData() {
        try {
            log.info("开始清理所有传感器历史数据");
            
            int thsDeletedCount = cleanupThsHistoryData();
            int lxDeletedCount = cleanupLxHistoryData();
            
            String result = String.format("历史数据清理完成 - 温湿度传感器: %d条, 照度传感器: %d条, 总计: %d条", 
                    thsDeletedCount, lxDeletedCount, thsDeletedCount + lxDeletedCount);
            
            log.info(result);
            
            return result;
        } catch (Exception e) {
            log.error("清理所有传感器历史数据异常", e);
            return "历史数据清理失败: " + e.getMessage();
        }
    }
} 